class UsersController < ApplicationController

  before_action :login_auth, only: [:destroy, :show, :index, :edit, :update, :user_bills]
  # before_action :login_auth

  def index
    Rails.logger.debug "session = #{session[:user_id]}"
  end

  def show
    mybills_page = params[:mypage] ? params[:mypage] : 1
    @user = User.find(params[:id])
    @note = Note.user_note(@user.id).first
    @count = @user.bills.count
    @mybills = @user.bills.page(mybills_page).per(15)
  end

  def new
    @user = User.new
    # @bills = Bill
  end

  def edit
    @att = Attachment.user_avatar(current_user.id).last
  end

  def update
    Rails.logger.debug "params = #{params}"
    args = params[:user]
    if args[:old_password] != ""
      if auth_user current_user, args[:old_password]
        password_digest = User.password_digest(args[:new_password])
        current_user.update(password: password_digest)
      else
        flash[:notice] = "old password wrong!"
        redirect_to edit_user_path
        return
      end
    end
    current_user.update(name: args[:name])
    if args[:avatar]
      attachement = Attachment.new
      attachement.user_id = current_user.id
      attachement.avatar = args[:avatar]
      attachement.tag = "img"
      attachement.save
    end
    flash[:notice] = "update user info success"
    redirect_to user_path(current_user)
  end

  def create
    @user = User.new(user_params)
    # @user.notes.build(payment: 0.0, total: 0.0, kind: "zero")
    if @user.save
      generate_username_default_icon(@user.name)
      login @user
      BillsMail.welcome_email(@session).deliver_later
      # EmailAsynJob.perform_later(@user)
      redirect_to user_path(@user)
    else
      render :new
    end
  end

  def user_bills
    @user = current_user
    unless current_user.group_id
      flash[:notice] = "please join into a group!"
      redirect_to groups_path
      return
    end
    page = params[:page] ? params[:page] : 1
    @group = current_user.group
    @group_users = @group.users
    @new_bill = Bill.new
    @bills = Bill.order(created_at: :desc).page(page).per(10)
    @att = Attachment.user_avatar(current_user.id).last

  end

  def destroy
  end

  private
  def user_params
    params.require(:user).permit(:email, :name, :password)
  end
end
